package net.siufung.market.base.dept.controller.regulation;

import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import net.siufung.core.exception.BizServiceException;
import net.siufung.core.model.VerifyRepeatDto;
import net.siufung.core.model.enums.MethodEventEnum;
import net.siufung.core.model.regulation.AbstractRegulation;
import net.siufung.core.utils.StringPool;
import net.siufung.market.base.dept.controller.model.dto.DeptSaveDto;
import net.siufung.market.base.dept.mapper.IDeptMapper;

import java.util.Objects;

/**
 * @author 陈建峰
 * @since 2022/7/31 10:48 下午
 */
@AllArgsConstructor
public class DeptCreateRegulation extends AbstractRegulation<DeptSaveDto> {

    private static final long serialVersionUID = 1309849500591098343L;

    private final IDeptMapper deptMapper;

    @Override
    public boolean isSatisfiedBy(DeptSaveDto deptSaveDto) {
        VerifyRepeatDto<String> verifyRepeatDto = new VerifyRepeatDto<>();
        verifyRepeatDto.setMethodEventEnum(MethodEventEnum.ADD);
        verifyRepeatDto.setPk(null);
        verifyRepeatDto.setVerifyKeyValue(deptSaveDto.getDeptName());
        if(!deptMapper.checkDeptNameNotRepeat(verifyRepeatDto)){
            throw new BizServiceException("部门名称重复！");
        }
        if(!Strings.isNullOrEmpty(deptSaveDto.getDeptCode())){
            verifyRepeatDto.setVerifyKeyValue(deptSaveDto.getDeptCode());
            if(!deptMapper.checkDeptCodeNotRepeat(verifyRepeatDto)){
                throw new BizServiceException("部门编码重复！");
            }
        }
        if(!StringPool.ZERO.equals(deptSaveDto.getParentId())){
            if(Objects.isNull(deptMapper.selectById(deptSaveDto.getParentId()))){
                throw new BizServiceException("父级部门不存在！");
            }
        }
        return Boolean.TRUE;
    }
}
